package com.example.zookeeper;

import org.apache.zookeeper.*;

import java.io.IOException;

public class watcherDemo implements Watcher {

    private static ZooKeeper zooKeeper;
    private static String path = "/watcher";

    @Override
    public void process(WatchedEvent watchedEvent) {
        System.out.println(watchedEvent.getPath() +"  --  " + watchedEvent.getType());

        String p = watchedEvent.getPath();

        if (watchedEvent.getType() == Event.EventType.NodeDataChanged){
            try {
                zooKeeper.exists(p, true);
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {

        String url = "192.168.232.130:2181,192.168.232.130:2182,192.168.232.130:2183";
        zooKeeper = new ZooKeeper(url,4000, new watcherDemo());

        if (zooKeeper.exists(path, false) == null){
            zooKeeper.create(path, "0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            zooKeeper.create(path+"1", "0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            zooKeeper.create(path+"2", "0".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }
        Thread.sleep(1000);
        zooKeeper.exists(path, true);
        zooKeeper.exists(path+"1", true);
        zooKeeper.exists(path+"2", true);
        System.in.read();

    }
}
